/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package org.whuims.service.paragraph;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.whuims.entity.Paragraph;
import org.whuims.repository.jpa.ParagraphDao;
import org.whuims.service.account.ShiroDbRealm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Spring Bean的标识.
@Component
// 类中所有public函数都纳入事务管理的标识.
@Transactional
public class ParagraphService {

    private ParagraphDao paragraphDao;

    public Paragraph getParagraph(Long id) {
        return paragraphDao.findOne(id);
    }

    public void save(Paragraph entity) {
        paragraphDao.save(entity);
    }

    public void deleteByDocumentId(Long docId) {
        paragraphDao.deleteByDocumentId(docId);
    }

    public void save(List<Paragraph> entities) {
        paragraphDao.save(entities);
    }

    public void delete(Long id) {
        paragraphDao.delete(id);
    }

    public List<Paragraph> getAllParagraphs() {
        return (List<Paragraph>) paragraphDao.findAll();
    }

    public List<Paragraph> findTopParagraphs(int size) {
        Sort sort = new Sort(Direction.DESC, "id");
        PageRequest pr = new PageRequest(0, size, sort);
        return paragraphDao.findAll(pr).getContent();
    }

    public Page<Paragraph> getParagraphList(Map<String, Object> searchParams, int pageNumber, int pageSize,
                                            String sortType) {
        if (searchParams == null) {
            searchParams = new HashMap<>();
        }
        PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
        Specification<Paragraph> spec = buildSpecification(searchParams);
        return paragraphDao.findAll(spec, pageRequest);
    }

    public Iterable<Paragraph> findAll() {
        if (getCurrentUserName().toLowerCase().equals("admin")) {
            return paragraphDao.findAll();
        } else {
            Specification<Paragraph> spec = buildSpecification();
            return paragraphDao.findAll(spec);
        }
    }

    /**
     * 创建分页请求.
     */
    private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
        Sort sort = null;
        if (sortType == null) sortType = "auto";
        if ("auto".equals(sortType)) {
            sort = new Sort(Direction.DESC, "id");
        } else if ("title".equals(sortType)) {
            sort = new Sort(Direction.ASC, "order_in_document");
        }
        return new PageRequest(pageNumber - 1, pagzSize, sort);
    }

    /**
     * 创建动态查询条件组合.
     */
    private Specification<Paragraph> buildSpecification(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        if (!getCurrentUserName().toLowerCase().equals("admin")) {
            filters.put("userId", new SearchFilter("userId", SearchFilter.Operator.EQ, String.valueOf(getCurrentUserId())));
        }
        Specification<Paragraph> spec = DynamicSpecifications.bySearchFilter(filters.values(), Paragraph.class);
        return spec;
    }

    private Specification<Paragraph> buildSpecification() {
        Map<String, SearchFilter> filters = new HashMap<>();
        filters.put("userId", new SearchFilter("userId", SearchFilter.Operator.EQ, String.valueOf(getCurrentUserId())));
        Specification<Paragraph> spec = DynamicSpecifications.bySearchFilter(filters.values(), Paragraph.class);
        return spec;
    }

    @Autowired
    public void setParagraphDao(ParagraphDao paragraphDao) {
        this.paragraphDao = paragraphDao;
    }

    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null) {
            return null;
        } else
            return user.id;
    }

    private String getCurrentUserName() {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null)
            return null;
        else return user.loginName;
    }

}
